﻿using software.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace software.common
{
    /// <summary>
    /// 菜单树结构初始化
    /// </summary>
    public class InitMenu
    {
        private List<SysMenu> menuList = new List<SysMenu>();
        private String firstId;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="firstId">首菜单的父节点</param>
        /// <param name="menuList">菜单数据</param>
        public InitMenu(string firstId, List<SysMenu> menuList)
        {
            this.menuList = menuList;
            this.firstId = firstId;
        }
        //建立树形结构
        public List<SysMenu> builTree()
        {
            List<SysMenu> treeMenus = new List<SysMenu>();
            List<SysMenu> rootMenus = getRootNode();
            foreach (SysMenu menuNode in rootMenus)
            {
                SysMenu nodes = buildChilTree(menuNode);
                treeMenus.Add(nodes);
            }
            return treeMenus;
        }
        //获取根节点
        private List<SysMenu> getRootNode()
        {
            List<SysMenu> rootMenuLists = new List<SysMenu>();
            foreach (SysMenu menuNode in menuList)
            {
                if (menuNode.ParentId == firstId)
                {
                    rootMenuLists.Add(menuNode);
                }
            }
            return rootMenuLists;
        }
        //递归，建立子树形结构
        private SysMenu buildChilTree(SysMenu pNode)
        {
            List<SysMenu> chilMenus = new List<SysMenu>();
            if (pNode.IsLeaf == "0")
            {
                foreach (SysMenu menuNode in menuList)
                {
                    if (menuNode.ParentId == pNode.MenuId)
                    {
                        chilMenus.Add(buildChilTree(menuNode));
                    }
                }
                pNode.Children = chilMenus;
            }
            return pNode;
        }
    }
}
